package com.cskaoyan.order.service.remote;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.mall.order.dto.PayOrderSuccessRequest;
import com.cskaoyan.mall.order.dto.PayOrderSuccessResponse;
import com.cskaoyan.order.biz.constant.OrderConstants;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @auther cskaoyan
 * @date 2022/5/23:19:40
 */
@RestController
@Slf4j
public class PayOrderServiceImpl {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    StockMapper stockMapper;

    @RequestMapping(value = "/rpc/pay/success", method = RequestMethod.PUT)
    @Transactional
    public PayOrderSuccessResponse payOrderSuccess(@RequestBody PayOrderSuccessRequest request) {
        PayOrderSuccessResponse payOrderSuccessResponse = new PayOrderSuccessResponse();
        //  修改订单状态，扣减对应订单商品的锁定库存
        //更新订单状态
        try {
            Order order = new Order();
            order.setOrderId(request.getOrderId());
            order.setStatus(OrderConstants.ORDER_STATUS_PAYED);
            int affectedRows = orderMapper.updateByPrimaryKeySelective(order);
            //查询订单对应的商品，并且更新item表里的status
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(request.getOrderId());
            List<Long> ItemIdList = orderItems.stream().map(o -> o.getItemId()).collect(Collectors.toList());
            OrderItem orderItemForUpdateStatus = new OrderItem();
            Example example = new Example(OrderItem.class);
            example.createCriteria()
                    .andEqualTo("orderId", request.getOrderId());
            orderItemForUpdateStatus.setStatus(OrderConstants.ITEM_ORDER_STATUS_RELEASE);
            orderItemMapper.updateByExampleSelective(orderItemForUpdateStatus, example);

            //更新库存
            //添加行锁
            List<Stock> stocksForUpdate = stockMapper.findStocksForUpdate(ItemIdList);
            for (OrderItem orderItem : orderItems) {
                Long itemId = orderItem.getItemId();
                Integer num = orderItem.getNum();

                Stock stock = new Stock();
                stock.setItemId(itemId);
                stock.setLockCount(-num);
                stock.setStockCount(0L);
                stockMapper.updateStock(stock);
            }
            payOrderSuccessResponse.setCode(OrderRetCode.SUCCESS.getCode());
            payOrderSuccessResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            payOrderSuccessResponse.setCode(OrderRetCode.DB_EXCEPTION.getCode());
            payOrderSuccessResponse.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
            log.error("调用订单服务出现异常"+e);
            ExceptionProcessorUtils.wrapperHandlerException(payOrderSuccessResponse,e);
        }
        return payOrderSuccessResponse;
    }
}
